package cn.itcast.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName:cloud-demo
 * Description:
 *
 * @Create: 2024/7/19 15:25
 * @author: likl
 * @e-mail: likl1102@foxmail.com
 * @QQ: 2514927731
 */
@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求的参数
        ServerHttpRequest request = exchange.getRequest();
        // 2. 获取参数中的authorization参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String authorization = queryParams.getFirst("Authorization");
        // 3. 判断authorization参数是否和admin相等，相等则放行
        if ("admin".equals(authorization)) {
            return chain.filter(exchange);
        } else {
            // 4. 否则不放行
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }
}
